﻿using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Logging;

namespace Lztkdr.ParameterBinder
{
    public class AutoBinder : IModelBinder
    {
        static AutoBinder()
        {

        }

        private ILogger<AutoBinder> _logger;
        public AutoBinder(ILogger<AutoBinder> logger)
        {
            this._logger = logger;
        }


        internal readonly static ConcurrentDictionary<string, Lazy<ValueParser>> CacheParser = new ConcurrentDictionary<string, Lazy<ValueParser>>();

        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var parser = CacheParser.GetOrAdd(bindingContext.HttpContext.TraceIdentifier, new Lazy<ValueParser>(() =>
            {
                var obj = new ValueParser(this._logger, bindingContext);
                return obj;
            }));
            parser.Value?.ParsingSetValue(bindingContext);
            return Task.CompletedTask;
        }
    }
}
